import 'dart:ui';
import 'package:flutter/material.dart';

import 'Utils.dart';

// void _onSearch(String query) async {
//   List<String> result = await searchAssets(ParseGlobalFilePaths(),query);
//   setState(() {
//     _showResults = true;
//     _searchResults = result;
//   });
// }



class SearchPage extends StatefulWidget {
  final String backgroundImage;
  final String title;

  const SearchPage({
    Key? key,
    required this.backgroundImage,
    this.title = '请输入搜索关键词',
  }) : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with SingleTickerProviderStateMixin {
  bool _showResults = false;
  List<String> _searchResults = [];
  final TextEditingController _controller = TextEditingController();

  late final AnimationController _animationController;
  late final Animation<double> _positionAnimation;

  @override
  void initState() {
    super.initState();

    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );

    _positionAnimation = Tween<double>(begin: 0.4, end: 0.1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  void _onSearch(String query) async {
    List<String> result = await searchAssets(ParseGlobalFilePaths(), query);
    setState(() {
      _showResults = true;
      _searchResults = result;
    });
    _animationController.forward();
  }

  void _onTapSearchField() {
    if (!_showResults) {
      setState(() {
        _showResults = true;
      });
      _animationController.forward();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          color: Colors.white,
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: Stack(
        children: [
          Image.network(
            widget.backgroundImage,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
            errorBuilder: (_, __, ___) => Container(color: Colors.grey),
          ),
          Container(color: Colors.black.withOpacity(0.3)),
          AnimatedBuilder(
            animation: _positionAnimation,
            builder: (context, child) {
              return Positioned(
                top: screenHeight * _positionAnimation.value,
                left: 24,
                right: 24,
                child: Column(
                  children: [
                    if (!_showResults)
                      Text(
                        widget.title,
                        style: const TextStyle(
                          fontFamily: "JetBrainsMono",
                          color: Colors.white,
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    if (!_showResults) const SizedBox(height: 16),
                    _buildSearchBox(),
                  ],
                ),
              );
            },
          ),
          if (_showResults)
            Positioned(
              top: screenHeight * 0.20,
              left: 24,
              right: 24,
              bottom: 24,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: ListView.builder(
                      padding: const EdgeInsets.all(12),
                      itemCount: _searchResults.length,
                      itemBuilder: (context, index) {
                        return Card(
                          color: Colors.white.withOpacity(0.8),
                          child: ListTile(
                            title: Text(
                                style: TextStyle(
                                  fontFamily: "JetBrainsMono"
                                ),
                                _searchResults[index]
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildSearchBox() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.9),
        borderRadius: BorderRadius.circular(8),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Row(
        children: [
          Icon(Icons.search, color: Colors.grey[600]),
          const SizedBox(width: 8),
          Expanded(
            child: TextField(
              controller: _controller,
              decoration: const InputDecoration(
                hintText: '搜索...',
                border: InputBorder.none,
              ),
              onSubmitted: _onSearch,
              onTap: _onTapSearchField,
            ),
          ),
        ],
      ),
    );
  }
}